// pages/uploading_img/uploading_img.js
const app = getApp()
var util = require("../../utils/utils.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    message: "",
    isSubmit: false,
    imageList: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "家长期待"
    })
    this.setData({
      activityChildId: options.activityChildId
    })
    this.queryChildInfo();
    this.queryValidAttachList();
  },
  queryChildInfo: function () {
    var that = this;
    wx.request({
      url: app.httpUrl + '/activity/queryChildInfo',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        activityChildId: this.data.activityChildId
      },
      success: (res) => {
        if (res.data.code == '000') {
          if (res.data.data != null) {
            that.setData({
              activity: res.data.data
            })
            this.queryBindChild();
          }
        }
      }
    })
  },
  queryBindChild: function () {
    let that = this;
    wx.request({
      url: app.httpUrl + '/user/queryBindChild',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: (res) => {
        for(var i in res.data) {
          if(res.data[i].childName == that.data.activity.childName) {
            that.setData({ parentChild: res.data[i] });
            break;
          }
        }
      }
    })
  },
  queryValidAttachList: function () {
    var that = this;
    wx.request({
      url: app.httpUrl + '/activity/live/queryValidAttachList',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "post",
      data: {
        operatorId: app.globalData.appUser.userInfo.id,
        attachType: 'image',
        relationType: 'parentExpect'
      },
      success: (res) => {
        if (res.data.code == '000') {
          if (res.data.data != null) {
            that.setData({ imageList: res.data.data })
          }
        }
      }
    })
  },
  delAttach: function (event) {
    var id = event.currentTarget.dataset.key;
    var that = this;

    wx.showModal({
      title: '删除图片',
      content: '确认删除此图片?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.httpUrl + '/activity/live/delActivityAttach',
            header: {
              'xcx-xtoken': app.globalData.openid,
              'content-type': 'application/json' // 默认值
            },
            method: "post",
            data: {
              id: id
            },
            success: (res) => {
              if (res.data.code == '000') {
                var imageList = that.data.imageList;
                for (var i in imageList) {
                  if (imageList[i].id == id) {
                    imageList.splice(i, 1);
                    break;
                  }
                }
                if (res.data.data != null) {
                  that.setData({ imageList: imageList })
                }
              }
            }
          })
        } else if (res.cancel) {

        }
      }
    })
  },
  wxChooseImage: function (e) {
    var that = this;
    var count = this.data.imageList;
    wx.chooseImage({
      count: 9 - count, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        var data = { paths: tempFilePaths };
        wx.showLoading({
          title: '上传中...',
        })
        that.uploadImage(data);
      }
    })
  },
  uploadImage: function (data) {
    var that = this,
      i = data.i ? data.i : 0,//当前上传的哪张图片
      success = data.success ? data.success : 0,//上传成功的个数
      fail = data.fail ? data.fail : 0;//上传失败的个数
    wx.uploadFile({
      url: app.httpUrl + '/attach/addActivityAttch',
      filePath: data.paths[i],
      name: 'file',
      formData: {
        'activityId': that.data.activity.activityId,
        'attachType': 'image',
        'relationType': 'parentExpect',
        'operatorId': that.data.parentChild.parentId,
      },
      header: {
        'xcx-xtoken': app.globalData.openid,
        "content-type": "multipart/form-data"
      },
      success: function (res) {
        var model = JSON.parse(res.data);
        if (model.code == '000') {
          success++;
          var imageList = that.data.imageList;
          imageList.push(model.data);
          that.setData({ imageList: imageList })
        }
      },
      fail: function (res) {
        fail++;
      },
      complete: function (res) {
        i++;
        if (i == data.paths.length) {   //当图片传完时，停止调用      
          console.log('执行完毕');
          console.log('成功：' + data.success + " 失败：" + data.fail);
          wx.hideLoading();
        } else {//若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadImage(data);
        }
      }
    })
  },
  addMessage: function () {
    var that = this;
    if (this.data.message.length == 0) {
      wx.showToast({
        title: '别忘了写下您的期待哦~',
        icon: 'none',
        duration: 3000
      });
      return;
    }
    if (this.data.isSubmit) return;
    this.setData({ isSubmit: true});
    wx.request({
      url: app.httpUrl + '/activity/live/addChildGrowthExpect',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "post",
      data: {
        message: this.data.message,
        activityId: this.data.activity.activityId,
        activityChildId: this.data.activityChildId,
        parentChildId: this.data.parentChild.id
      },
      success: (res) => {
        if (res.data.code == '000') {
          wx.showToast({ title: '提交成功！', icon: 'success', duration: 3000 });
          that.setData({
            message: '',
            imageList: []
          })
          setTimeout(function() {
            wx.switchTab({
              url: '/pages/study/study'
            })
          }, 3000);
        } else {
          wx.showToast({ title: "提交失败!", icon: 'none', duration: 3000 });
          this.setData({ isSubmit: false });
        }
      }
    })
  },
  previewImage: function (event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var list = this.data.imageList;
    var urls = [];
    for (var i in list) {
      urls.push(app.imgUrl + list[i].attachUrl);
    }
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: urls // 需要预览的图片http链接列表     
    })
  },
  messageInputs: function (e) {
    // 获取输入框的内容
    var value = e.detail.value;
    this.setData({
      message: value
    })
  }
})